<template>
    <div class="app-container">
        <!--工具栏-->
        <div class="head-container">
        
            
            <div v-if="crud.props.searchToggle">
                <!-- 搜索 -->
                <el-input v-model="query.blurry" clearable size="small" placeholder="设备名称或者mac地址模糊搜索" style="width: 230px;"
                             class="filter-item" @keyup.enter.native="toQuery" />
                
                <el-select v-model="query.userId" clearable class="filter-item" style="width: 150px" 
                                        placeholder="请选择关联用户" @change="crud.toQuery" filterable>
                    <el-option
                    v-for="(item, index) in users"
                    :key="item.phone + index"
                    :label="item.phone"
                    :value="item.uid"
                    />
                </el-select>
               

                <el-select v-model="query.userId" clearable class="filter-item" style="width: 150px" placeholder="请选择关联用户" @change="crud.toQuery" filterable>
                    <el-option
                    v-for="(item, index) in users"
                    :key="item.username + index"
                    :label="item.username"
                    :value="item.uid"
                    />
                </el-select>

                <el-select v-model="query.equipmentTypeId" style="width: 150px" clearable class="filter-item"
                                                  placeholder="请选择设备类型" @change="crud.toQuery" filterable>
                    <el-option
                    v-for="(item, index) in equipmentTypes"
                    :key="item.equipmentTypeName + index"
                    :label="item.equipmentTypeName"
                    :value="item.id"
                    />
                </el-select>
                <rrOperation :crud="crud"/>
            </div>

            <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
            <!-- <crudOperation :permission="permission"/> -->
            <!--表单组件-->
            <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
                       :title="crud.status.title" width="500px">
                <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
                    <el-form-item label="设备名称" prop="equipmentName">
                        <el-input v-model="form.equipmentName" style="width: 370px;"/>
                    </el-form-item>
                    <el-form-item label="关联用户" prop="userId">
                        <el-select v-model="form.userId" style="width: 370px" 
                                 placeholder="请选择用户" @change="getAgent" clearable filterable>
                            <el-option
                            v-for="(item, index) in users"
                            :key="item.phone + index"
                            :label="item.phone"
                            :value="item.uid"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备类型" prop="equipmentTypeId">
                        <el-select v-model="form.equipmentTypeId" style="width: 370px" 
                                 placeholder="请选择设备类型" @change="getEquipmentType">
                            <el-option
                            v-for="(item, index) in equipmentTypes"
                            :key="item.equipmentTypeName + index"
                            :label="item.equipmentTypeName"
                            :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="mac地址" prop="macAddress">
                        <el-input v-model="form.macAddress" style="width: 370px;"/>
                    </el-form-item>
                    <el-form-item label="批次号">
                        <el-input v-model="form.batchNo" style="width: 370px;"/>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="text" @click="crud.cancelCU">取消</el-button>
                    <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
                </div>
            </el-dialog>
            
            <!--表格渲染-->
            <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                      @selection-change="crud.selectionChangeHandler">
                <el-table-column type="selection" width="55"/>
                <!--<el-table-column v-if="columns.visible('id')" prop="id" label="ID"/>-->
                <el-table-column v-if="columns.visible('equipmentName')" prop="equipmentName" label="设备名称"/>
                <el-table-column v-if="columns.visible('userName')" prop="userName" label="关联用户"/>
                <el-table-column v-if="columns.visible('equipmentTypeName')" prop="equipmentTypeName" label="设备类型" min-width="60px"/>
                <el-table-column v-if="columns.visible('macAddress')" prop="macAddress" label="mac地址"/>
                <el-table-column v-if="columns.visible('batchNo')" prop="batchNo" label="批次号" min-width="50px"/>
                <el-table-column v-if="columns.visible('createTime')" prop="createTime" label="创建时间">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column v-if="columns.visible('updateTime')" prop="updateTime" label="更新时间">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.updateTime) }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column v-permission="['admin','equipment:edit','equipment:del']" label="操作" width="120px" align="center">
                    <template slot-scope="scope">
                        <udOperation :data="scope.row" :permission="permission"/>
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" width="160px" align="center" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" style="margin-right: 2px" type="text">
                      <router-link :to="{name:'deviceControl'}">
                        去授权
                      </router-link>
                    </el-button>
                  </template>
                </el-table-column>
            </el-table>
            <!--分页组件-->
            <pagination/>
        </div>
    </div>
</template>

<script>
    import crudEquipment from '@/api/storeEquipment'
    import MaterialList from "@/components/material";
    import CRUD, { presenter, header, form, crud } from '@crud/crud'
    import rrOperation from '@crud/RR.operation'
    import crudOperation from '@crud/CRUD.operation'
    import udOperation from '@crud/UD.operation'
    import pagination from '@crud/Pagination'
    import { getAllMemberUser } from '@/api/memberUser'
    //import { getAllAgent } from '@/api/agentMember'
    import { getAllEquipmentType } from '@/api/equipmentType'
   

    // crud交由presenter持有
    const defaultCrud = CRUD({ title: '设备', url: 'api/equipment/agent', sort: 'id,desc', crudMethod: { ...crudEquipment }})
    
    const defaultForm = { id: null, equipmentName: null, userId: null, equipmentTypeId: null, macAddress: null, batchNo: null, ip: null, status: null, isOnline: null }
    export default {
        name: 'Equipment',
        components: {pagination, crudOperation, rrOperation, udOperation, MaterialList},
        mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
        data() {
            return {
                users: [],
                equipmentTypes: [],
                permission: {
                    // add: ['admin', 'equipment:add'],
                    // edit: ['admin', 'equipment:edit'],
                    // del: ['admin', 'equipment:del']
                },
                rules: {
                    equipmentName: [
                        { required: true, message: '请输入设备名', trigger: 'blur' },
                        { min: 2, max: 20, message: '长度在 2 到 40 个字符', trigger: 'blur' }
                    ],
                    macAddress: [
                        { required: true, message: '请输入设备名mac地址', trigger: 'blur' },
                        { min: 2, max: 20, message: '长度在 2 到 40 个字符', trigger: 'blur' }
                    ]
                },
                BASE_API: process.env.VUE_APP_BASE_API, // 接口API地址
                fileUploadBtnText: '上传到服务器', // 按钮文字
                importBtnDisabled: false, // 按钮是否禁用,
                loading: false           
            }
        },
        watch: {
        },
        mounted:function(){ //在页面加载参数结束后执行某个函数
            this.$nextTick(function(){
                //调用需要执行的方法
                //this.getAgent()
                this.getMemberUser()
                this.getEquipmentType()
            })      
        },
        methods: {
            // 新增与编辑前做的操作
            [CRUD.HOOK.afterToCU](crud, form) {
            },
            // 提交前的验证
            [CRUD.HOOK.afterValidateCU](crud) {
                if (!crud.form.userId) {
                    this.$message({
                    message: '关联用户不能为空',
                    type: 'warning'
                    })
                    return false
                } else if (!crud.form.equipmentTypeId) {
                    this.$message({
                    message: '设备类型不能为空',
                    type: 'warning'
                    })
                    return false
                }
                return true
            },
            checkboxT(row, rowIndex) {
                return row.id !== 1
            },
            getAgent() {
                getAllAgent(data).then(res => {
                    console(data)
                    this.users = res
                }).catch(() => { })
            },
            getMemberUser() {
                getAllMemberUser().then(res => {
                    this.users = res
                }).catch(() => { })
            },
            downloadFile1(obj, name, suffix) {
                console.log(obj);
                const url = window.URL.createObjectURL(new Blob([obj]))
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                const fileName = parseTime(new Date()) + '-' + name + '.' + suffix
                link.setAttribute('download', fileName)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                console.log('test2');
            },
            downloadTemplate() {
                window.location.href = 'https://shopmall0508.oss-cn-shenzhen.aliyuncs.com/2023/05/09/75f86fd6584545dbbaa40d7f8727dc9adevices_data_import.xlsx'
            },
            getEquipmentType() {
                getAllEquipmentType().then(res => {
                    this.equipmentTypes = res
                }).catch(() => { })
            },submitUpload() {
                this.fileUploadBtnText = '正在上传'
                this.importBtnDisabled = true
                this.loading = true
                this.$refs.upload.submit()
            },
            fileUploadSuccess(response) {
                if (response.code === 0) {
                    this.fileUploadBtnText = '导入成功'
                    this.importBtnDisabled = false //启用导入按钮
                    this.loading = false
                    this.$message({
                        type: 'success',
                        message: '导入成功'
                    })
                } else if (response.code === -1) {
                    this.fileUploadBtnText = '上传服务器'
                    this.importBtnDisabled = false //启用导入按钮
                    this.loading = false
                    this.$message({
                        type: 'error',
                        message: response.msg
                    })
                }
                this.crud.refresh()//刷新数据
            },
            fileUploadError(response) {
                this.fileUploadBtnText = '上传服务器'
                this.importBtnDisabled = false //启用导入按钮
                this.loading = false
                this.$message({
                    type: 'error',
                    message: '导入失败'
                })
                this.crud.refresh()//刷新数据
            }
        }
    }


</script>

<style scoped>
    .table-img {
        display: inline-block;
        text-align: center;
        background: #ccc;
        color: #fff;
        white-space: nowrap;
        position: relative;
        overflow: hidden;
        vertical-align: middle;
        width: 32px;
        height: 32px;
        line-height: 32px;
    }

</style>
